#include <stdio.h>
#include <fcntl.h>
#include <time.h>
#include <sys/mman.h>

/*
[chenndao@localhost log]$ ./maplogread 3000000.txt
Finished, total lines is 3000000
total costed time 0 sec
[chenndao@localhost log]$ ./maplogread 3000000.txt
Finished, total lines is 3000000
total costed time 1 secs
*/

/*#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>*/
int writeshared(char * s,short m,short flag,int Ampltitude );

int main(int argc,char* argv)
{
    void *pmap;
    char *s;
    sprintf(&s,"%s",&argv[1]);

    int i=writeshared(&s,20,1,20);
    if(0!=i) return i;
    i=readshared(&s,&pmap);
    return i;
}

int writeshared(char * s,short m,short flag,int Ampltitude )
{
    int i,k,n,m2[8];
    n=(1<<m);
    int j=(~(~0<<(Ampltitude-1)));
    int jj=0;
    float f1,f2,f3;
    FILE *fp;
    fp = fopen(&s,"w+");
    if(fp==NULL)
    {
        printf("Create File Error.\n") ;
        return 0;
    }
    fprintf(fp,"short Sinewave[N_WAVE-N_WAVE/4] = {\n");
    f1=atan(1)*2;

    while(jj<n)
    {
        for(k=0; k<8; k++)
        {
            f3=(float)jj / n *flag;
            f2=sin(f1*f3);
            m2[k]=f2 * j;
            fprintf(fp,"%d,",m2[k]);
            jj++;
        }
        fprintf(fp, "\n");
    }
    fprintf(fp, "}\n");
    fclose(fp);

    return 0;
}

int readshared(char* DATA_FILE,void *pMap)
{
    char *memory = NULL;
    int file_length = 0;
    char *start_address = 0;
    int line_num = 0;
    int time_start = time(NULL);
    int fd = open(&DATA_FILE, O_RDWR|O_RSYNC );
    if(fd==-1)
    {
        printf("Open DataFile  Error!\n%s",DATA_FILE);
        return 0 ;
    }
    if ( fd > 0 )
    {
        file_length = lseek(fd, 1, SEEK_END);
        memory = mmap( start_address, file_length, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0 );
        if(memory==MAP_FAILED)
        {
            printf("Map file to Virtual Memory Error!\n");
            close(fd);
            return 0;
        }
        int i=0;
        for ( ; i<file_length; i++ )
        {
            if ( memory[i] == '\n' )
            {
                ++line_num;
            }
        }

        close( fd );
        munmap( memory, file_length );
        printf("Finished, total lines is %d \n", line_num);
        printf("total costed time %d sec\n", time(NULL) - time_start);
    }
    return 0;

}
